package com.unitd.base.module.consumer.controller;

import com.google.common.collect.Maps;
import com.unitd.base.frame.plugin.module.dto.ResponseUtils;
import com.unitd.base.frame.util.BeanUtils;
import com.unitd.base.module.consumer.comm.annotation.LoginUser;
import com.unitd.base.module.consumer.comm.controller.ApiBaseAction;
import com.unitd.base.module.master.pojo.dto.CompanyDatasourceVO;
import com.unitd.base.module.master.pojo.dto.UserVO;
import com.unitd.base.module.master.service.CompanyDatasourceService;
import com.unitd.base.module.master.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 数据源信息管理前端控制器类
 *
 * @author hudan
 * @version 1.0
 * @filename ApiDatasourceController.java
 * @copyright www.symdata.cn
 * @date 2020-07-08
 */
@Api(tags = "A-数据源管理")
@RestController
@RequestMapping("/api/datasource")
public class ApiDatasourceController extends ApiBaseAction {

    @Autowired
    private UserService userService;
    @Autowired
    private CompanyDatasourceService companyDatasourceService;

    /**
     * 登录用户获取需要绑定的数据源列表
     *
     * @param loginUser 当前登录用户
     * @return 需要绑定的数据源列表
     */
    @ApiOperation(value = "登录用户获取需要绑定的数据源列表")
    @PostMapping(value = "list")
    public Map<String, Object> list(@LoginUser UserVO loginUser) {
        if (BeanUtils.isNull(loginUser) || loginUser.getUserId() <= 0) {
            return ResponseUtils.toResponsFail("登录失败");
        }

        // 获取当前登录用户所在公司的默认数据源
        List<CompanyDatasourceVO> datasources = companyDatasourceService.selectByCompanyId(loginUser.getCompanyDatasource().getCompanyId());
        return ResponseUtils.toResponsSuccess(datasources);
    }

    /**
     * 登录用户绑定指定数据源
     *
     * @param loginUser 当前登录用户
     * @return 登录结果
     */
    @ApiOperation(value = "登录用户绑定数据源")
    @PostMapping(value = "bind")
    public Map<String, Object> doBindDatasource(@LoginUser UserVO loginUser, @RequestParam Long datasourceId) {
        // 当前登录用户
        long userId = loginUser.getUserId();

        // 设置用户默认数据源
        int result = userService.setUserDefDatasource(userId, datasourceId);

        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("bindResult", result == 2);
        return ResponseUtils.toResponsSuccess(resultMap);
    }
}